import { createRouter, createWebHistory } from "vue-router";
import { message } from "ant-design-vue";

const routes = [
  {
    path: "/",
    redirect: {
      name: "login"
    }
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/Login.vue")
  },
  {
    path:"/productDetailsUser/:puid",
    name:"productDetailsUser",
    meta:{title:"农产品详细信息"},
    component:()=>import("../views/secondPage/product/ProductDetail.vue")
  },
  {
    path:"/index",
    name:"index",
    meta:{title:"首页",keepAlive:true},
    component:()=>import("../views/Index/Index.vue"),
    children:[
      {
        path:"/home",
        name:"home",
        meta:{title:"时间线"},
        component:()=>import("../views/secondPage/Home.vue")
      },
      {
        path:"/products",
        name:"products",
        meta:{title:"农产品信息"},
        component:()=>import("../views/secondPage/product/Product.vue"),
        children:[
        ]
      },
      {
        path:"/users",
        name:"users",
        meta:{title:"所有用户信息"},
        component:()=>import("../views/AdminPage/Users.vue")
      },
      {
        path:"/check",
        name:"check",
        meta:{title:"检测结果"},
        component:()=>import("../views/secondPage/product/Check.vue")
      },
      {
        path:"/position",
        name:"position",
        meta:{title:"产品运输"},
        component:()=>import("../views/secondPage/product/Position.vue")
      },
      {
        path:"/productDetails/:puid",
        name:"productDetails",
        meta:{title:"农产品详细信息"},
        component:()=>import("../views/secondPage/product/ProductDetail.vue")
      },
      {
        path:"/type",
        name:"type",
        meta:{title:"产品类型"},
        component:()=>import("../views/secondPage/product/Type.vue")
      },
      {
        path:"/userInfo",
        name:"userInfo",
        meta:{title:"个人用户信息"},
        component:()=>import("../views/secondPage/UserInfo.vue")
      },
      {
        path:"/history",
        name:"history",
        meta:{title:"历史记录"},
        component:()=>import("../views/secondPage/product/History.vue")
      },
    ]
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  //to将要访问的路径
  //from代表从那个路径跳转而来
  //next是一个函数，表示放行
  //next（）放行 next(’/login’)强制跳转

  //获取token
  const localtokenStr = window.localStorage.getItem('token')
  const sessiontokenStr = window.sessionStorage.getItem('token')

  if(to.path.startsWith("/productDetailsUser/")){
    return next()
  }

  if (to.path === '/login') {
    if(localtokenStr!=null||sessiontokenStr!=null){
      return next("/index")
    }
    else{
      return next()
    }
  }
  
  if (localtokenStr==null && sessiontokenStr==null) {
    console.log(to.path)
    message.error('身份验证失败！')
    return next('/login')
  }
  return next()
})

export default router;
